package com.wk.database;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/***
 * 得到一个省份编号与机器的对应表
 * @author wkhua
 *
 */
public class MachinesMap {
	
	Properties relations = new Properties();;
	private String propertieFile = "info/machineMap.properties";
	
	public MachinesMap(){
		
	}
	

	public MachinesMap(String propertiesFile) {
		this.propertieFile = propertiesFile;
	}
	
	/***
	 * 从数据库初始化省份与机器的映射关系
	 * @param idToMachine2
	 * @return
	 */
	public boolean initFromDataBase(IdToMachine idToMachine){
		
		if(!DB_Mysql.refreshMachinesInfo(idToMachine)){
			return false;
		}
		return true;
	}
	
	/***
	 * 从配置文件初始化 省份与机器的映射关系
	 * 
	 * @param idToMachine2 key: 省份编号例如53 value: 地址 格式 127.0.0.1:8080
	 * @return
	 */
	public boolean initFromProperties(IdToMachine idToMachine) {
		
		FileInputStream in;
		try {
			File file = new File(propertieFile);
			if(!file.exists()){
				return false;
			}
			in = new FileInputStream(file);
			relations.load(in);
			Set<Object> keys = relations.keySet();
			for(Object key : keys){
				String str = (String)key;
				idToMachine.put(str, relations.getProperty(str));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	
	}
	
	/***
	 * 从配置文件初始化 省份与机器的映射关系
	 * 
	 * @param idToMachine2 key: 省份编号例如53 value: 地址 格式 127.0.0.1:8080
	 * @return
	 */
	@Deprecated
	public boolean initFromProperties(Map<String, String> idToMachine2) {
		
		FileInputStream in;
		try {
			File file = new File(propertieFile);
			if(!file.exists()){
				return false;
			}
			in = new FileInputStream(file);
			relations.load(in);
			Set<Object> keys = relations.keySet();
			for(Object key : keys){
				String str = (String)key;
				idToMachine2.put(str, relations.getProperty(str));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	
	}
	public String getPropertieFile() {
		return propertieFile;
	}
	public void setPropertieFile(String propertieFilePath) {
		this.propertieFile = propertieFilePath;
	}
}
